<template>
  <div>
    <el-dialog
      v-el-drag-dialog="{ resize: resizeChart, updataFull, updataDialogWidth }"
      :fullscreen="isfullscreen"
      :append-to-body="true"
      :width="setDialogWidth('1200px')"
      :visible="visible"
      @open="open"
      @close="close"
    >
      <template slot="title">
        <span class="el-dialog__title">{{ this.$t('DETAILS') }}</span>
        <!-- <span class="text-danger">
          {{ errMsg }}
        </span> -->
      </template>
      <div id="printHtml" class="printHtml">
        <div class="flex">
          <line-chart
            id="record-line"
            ref="recordLine"
            v-loading.fullscreen.lock="loading"
            class="flex-1 mr-10 w-1 mb-10"
            style="height: 300px"
            :row-list="rowList"
            @legendselectchanged="legendselectchanged"
          />
          <div style="width: 40%">
            <div class="test-message p-10" style="height: 80%">
              <h4>
                {{ $t('TEST_PARA') }}
              </h4>
              <div class="flex flex-wrap">
                <span class="w-100"> {{ $t('TEST_NAME') }}：{{ testName }} </span>
                <span> {{ $t('TEST_MODE') }}：{{ getTestType(criteria.testMode) }} </span>
                <span> {{ $t('JOINT_LOSS_THRESHOLD') }}：{{ criteria.lossThreshold }}</span>
                <span> {{ $t('WAVELENGTH') }}：{{ criteria.waveLength }} </span>
                <span> {{ $t('ENV_REFLECTION_THR') }}：{{ criteria.reflectThreshold }} </span>
                <span>
                  {{ $t('TEST_RANGE') }}：{{ changeDecimal(Number(criteria.testRange) / 1000) }}
                </span>
                <span> {{ $t('FIBER_END_THR') }}：{{ criteria.endThreshold }} </span>
                <span> {{ $t('PULSE_WIDTH') }}：{{ criteria.pulseWidth }} </span>
                <span> {{ $t('CORRECTION_PARA') }}：{{ criteria.fixParam }} </span>
                <span class="mb-10"> {{ $t('INDEX') }}：{{ criteria.refractRate }} </span>
                <span class="mb-10"> {{ $t('TEST_NUMBER') }}：{{ criteria.testNum }} </span>
                <span v-if="permission.saveCurve && rowData.bizType !== 'BIZ_THROUGH' && !isIotTest">
                  <el-button
                    type="primary"
                    size="mini"
                    icon="iconfont icon-AFSquxian"
                    :disabled="detailData.isRefCurve"
                    @click="setRefCurve"
                  >
                    {{ $t('SAVE_CURVE') }}
                  </el-button>
                  <el-popover width="200" trigger="hover">
                    <div class="text-color" v-html="$t('SAVE_FOR_ROUTINE')" />
                    <i
                      slot="reference"
                      class="iconfont icon-AFSwenhao text-color ml-5 font-weight-normal"
                    />
                  </el-popover>
                </span>
                <span>
                  <el-button
                    v-if="permission.saveTemplate && (!rowData.isBizOtdrResult || isIotTest)"
                    type="primary"
                    size="mini"
                    icon="iconfont icon-AFSyewuguanli"
                    :disabled="detailData.isTemp"
                    @click="templateShow"
                  >
                    {{ $t('SAVE_TEMPLATE') }}
                  </el-button>
                </span>
              </div>
            </div>
            <div class="test-message-bottom">
              <div>
                <i class="iconfont icon-AFSceju" />
                <div>
                  <h6>
                    {{
                      changeDecimal(
                        detailData.fiberLength ? detailData.fiberLength / 1000 : 0,
                        3,
                        true
                      )
                    }}km
                  </h6>
                  <p>{{ $t('CABLE_LENGTH').replace('(km)', '') }}</p>
                </div>
              </div>
              <div>
                <i class="iconfont icon-AFSsunhao" />
                <div>
                  <h6>
                    {{
                      !detailData.totalLoss || detailData.totalLoss > 990000
                        ? '--'
                        : changeDecimal(detailData.totalLoss, 3)
                    }}dB
                  </h6>
                  <p>{{ $t('LINK_LOSS') }}</p>
                </div>
              </div>
              <div>
                <i class="iconfont icon-AFSicon-average" />
                <div>
                  <h6>
                    {{
                      !detailData.avgLoss || detailData.avgLoss > 990000
                        ? '--'
                        : changeDecimal(detailData.avgLoss, 3)
                    }}dB/km
                  </h6>
                  <p>{{ $t('AVERAGE_LOSS') }}</p>
                </div>
              </div>
            </div>
          </div>
        </div>
        <event-table id="eventTable" :row-list="rowList" :legend-select="legendSelect" />
      </div>

      <template v-slot:footer>
        <!-- <el-button
          type="primary"
          @click="$debounce(pringReport)"
        >{{ $t('PRINTREPORTS') }}</el-button> 暂时保留不使用-->
        <el-button
          v-if="permission.exportlist && detailData.eventList && detailData.eventList.length"
          type="primary"
          @click="$debounce(exportChannel)"
        >{{ $t('EXPORT_LIST') }}</el-button>
        <el-button
          v-if="
            permission.scableLength &&
              !rowData.isBizOtdrResult &&
              rowData.cableIdList &&
              rowData.cableIdList.length === 1
          "
          @click="$debounce(updateCable)"
        >{{ $t('RENEW_CABLE_LENGTH') }}</el-button>
        <el-button @click="close">{{ $t('CLOSE') }}</el-button>
      </template>
    </el-dialog>
    <el-dialog
      append-to-body
      width="400px"
      :visible="showSaveTemplate"
      :title="this.$t('SAVE_TEMPLATE')"
      @close="showSaveTemplate = false"
    >
      <el-form
        ref="templateForm"
        label-width="90px"
        :model="templateData"
        class="pr-20"
        :rules="rules"
      >
        <el-form-item :label="$t('TPL_NAME')" prop="templateName">
          <el-input v-model.trim="templateData.templateName" maxlength="32" />
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <el-button @click="showSaveTemplate = false">{{ $t('CANCEL') }}</el-button>
        <el-button @click="$debounce(saveTemplate)">{{ $t('SAVE') }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import printJS from 'print-js'
  import html2canvas from 'html2canvas'
  import otdrTestResult from '@/api/oen/OtdrTestResult'
  import cableApi from '@/api/oen/CableApi'
  import paramApi from '@/api/system/ParamApi'
  import OperateLogApi from '@/api/system/OperateLogApi'
  import taskGroup from '@/api/oen/TaskGroup'
  import { changeDecimal } from '@/utils/common'
  import { tableToExcel } from '@/utils/jsonToExcel'
  import LineChart from './chart/LineChart'
  import EventTable from './EventTable'

  export default {
    components: { LineChart, EventTable },
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      rowData: {
        type: Object,
        default: () => {}
      }
    },
    inject: ['parentVM'],
    data() {
      return {
        templateData: {
          templateName: ''
        },
        showSaveTemplate: false,
        detailData: {
          avgLoss: 0,
          linkLoss: 0,
          totalLoss: 0,
          cableLength: 0,
          samplePrecision: 0
        },
        changeDecimal: changeDecimal,
        rowList: [],
        criteria: {}, // 测试条件
        referenceData: null,
        legendSelect: {},
        loading: false,
        errMsg: '',
        isIotTest: false
      }
    },
    computed: {
      ...mapGetters(['dictMap', 'getUser']),
      permission() {
        return this.$store.getters.getAuthData('link:record')
      },
      rules() {
        return {
          templateName: [
            {
              required: true,
              message: this.$t('PLEASE_INPUT') + this.$t('TPL_NAME'),
              trigger: 'blur'
            }
          ]
        }
      },
      testName() {
        let name = this.rowData.taskName
        if (this.rowData.bizType === 'BIZ_DETECT') {
          const typeLabel = this.rowData.bizId
            ? this.rowData.bizName + this.$t('BIZ_STATUS_RESTORE')
            : (this.rowData.deviceName || this.rowData.deviceId) + this.$t('OPEN')
          name = this.$t('PRE_OTDR_TEST', { msg: typeLabel })
        }
        return name
      }
    },
    methods: {
      pringReport() {
        html2canvas(document.getElementById('printHtml')).then(function(canvas) {
          const imageURL = canvas.toDataURL('image/png') // canvas转base64图片
          printJS({
            printable: imageURL,
            type: 'image',
            header: 'OTDR曲线报告',
            headerStyle: 'text-align:center;'
          })
        })
      },
      resizeChart() {
        this.$refs.recordLine && this.$refs.recordLine.resize()
      },
      open() {
        this.isIotTest =
          !this.rowData.bizType &&
          !this.rowData.testDirection &&
          !this.rowData.connPortId &&
          !this.rowData.fiberName
        this.rowData.isBizOtdrResult = !this.rowData.linkSegmentId
        this.detailData = { ...this.rowData }
        this.getData()
        if (
          !this.rowData.isBizOtdrResult &&
          this.permission.scableLength &&
          this.rowData.cableIdList &&
          this.rowData.cableIdList.length === 1
        ) {
          this.getCableLengthConfig()
        }
        console.log(this.rowData)
        console.log(this.parentVM.functionName)
      },
      getCableLengthConfig() {
        paramApi.page({ page: 1, size: 1, keyword: 'CABLE_LENGTH_COMPARE' }).then(res => {
          const configData = res.list ? res.list[0] : null
          if (configData && configData.enable) {
            const cableConfigData = JSON.parse(configData.paramValue || '{}')
            this.compareCableLength(cableConfigData)
          }
        })
      },
      async compareCableLength(configData) {
        const cableData =
          (await cableApi.getByCableId({ cableId: this.rowData.cableIdList[0] })) || {}
        const cableLength = changeDecimal(cableData.cableLength, 3, true)
        const fiberLength = changeDecimal(this.detailData.fiberLength / 1000, 3, true)
        const percent = changeDecimal((Math.abs(cableLength - fiberLength) * 100) / cableLength, 2)
        let differType = ''
        if (configData.greaterEnable && fiberLength > cableLength && percent > configData.greater) {
          differType = this.$t('EXCEED')
        }
        if (configData.lessEnable && fiberLength < cableLength && percent > configData.less) {
          differType = this.$t('SHORTER_THAN')
        }
        if (differType) {
          const message = this.$t('CABLE_LENGTH_ABNORMAL_CONFIRM', {
            differType: differType,
            fiberLength: fiberLength,
            cableLength: cableLength,
            percent: percent
          })
          this.$confirm(message, this.$t('CABLE_LENGTH_ABNORMAL'), {
            confirmButtonText: this.$t('RENEW_CABLE_LENGTH'),
            cancelButtonText: this.$t('CANCEL'),
            type: 'warning',
            dangerouslyUseHTMLString: true
          }).then(() => {
            this.updateCable()
          })
        }
      },
      getData() {
        this.loading = true
        this.referenceData = null
        this.errMsg = ''
        Promise.all([
          otdrTestResult.queryOne({
            taskId: this.rowData.taskId
          }),
          taskGroup.getByTaskId({
            taskId: this.rowData.taskId
          }),
          !this.rowData.isBizOtdrResult &&
            this.rowData.portId &&
            otdrTestResult.queryOne({
              portId: this.rowData.portId
            })
        ])
          .then(result => {
            this.getDetail({ ...this.rowData, ...result[0] })
            this.getReference(result[2])
            // console.log('this.referenceData', this.referenceData)
            // console.log('this.detailData', this.detailData)
            this.rowList = this.referenceData
              ? [this.detailData, this.referenceData]
              : [this.detailData]
            const _this = this
            setTimeout(() => {
              _this.$refs.recordLine.render()
              _this.loading = false
            }, 100)
          })
          .catch(err => {
            console.log(err)
          })
      },
      getDetail(res) {
        this.criteria = { testRange: 0 }
        if (!res) return
        res.orderIndex = res.orderIndex || 1
        // if (res.sampleNum !== res.dataList.length) {
        //   this.errMsg = this.$t('TEST_RESULT_ERROR', { time: res.endTime, typeName: '设备断电' })
        // }
        this.detailData = res
        // 图表数据
        this.detailData.dataList = this.formateData(res)
        // 表格数据
        this.detailData.eventList = this.formateEventList(res)
        // 测试条件
        this.criteria = res.testParam || {}
      },
      getReference(res) {
        if (!res) return
        this.referenceData = res
        // this.referenceData.orderIndex = 2
        this.referenceData.dataName = this.$t('REFERENCE_CURVE_LINE')
        // 图表数据
        this.referenceData.dataList = this.formateData(res)
        this.referenceData.eventList = this.formateEventList(res)
      },
      formateData(res) {
        if (!res.dataList) {
          return []
        }
        const chartData = []
        res.dataList.forEach((e, i) => {
          if (i * Number(res.samplePrecision) <= Number(res.testParam.testRange)) {
            chartData.push({
              value: [changeDecimal(i * res.samplePrecision, 2), e]
            })
          }
        })
        return chartData
      },
      formateEventList(data) {
        const eventList = data.eventList || []
        eventList.sort((a, b) => a.position - b.position)
        eventList.forEach((i, index) => {
          if (data.orderIndex) {
            i.index = 0
            i.portName = data.orderIndex + '_' + (data.deviceName || data.deviceId)
            this.legendSelect[i.portName] = true
          } else {
            i.index = 1
            i.portName = this.$t('REFERENCE_CURVE_LINE')
            this.legendSelect[i.portName] = false
          }
          i.intervalLoss = '-'
          i.intervalAverageLoss = '-'
          if (index !== 0) {
            i.intervalLoss = i.linkLoss - i.eventLoss - eventList[index - 1].linkLoss
            i.intervalAverageLoss =
              (i.intervalLoss * 1000) / (i.position - eventList[index - 1].position)
          }
        })
        return eventList
      },
      legendselectchanged(data) {
        this.legendSelect = data
      },
      // 设为参考曲线
      setRefCurve() {
        otdrTestResult
          .setRefCurve({
            taskId: this.rowData.taskId,
            portId: this.rowData.portId,
            deviceId: this.rowData.deviceId, // 操作日志需要传此参数
            portName: this.rowData.portName || '' // 操作日志需要传此参数
          })
          .then(res => {
            this.$message.success(this.$t('SAVE_SUCCESS'))
            this.detailData.isRefCurve = true
            this.$emit('loadData')
          })
      },
      templateShow() {
        this.templateData.templateName = ''
        this.$refs.templateForm && this.$refs.templateForm.clearValidate()
        this.showSaveTemplate = true
      },
      // 保存测试参数为模板
      saveTemplate() {
        this.$refs.templateForm.validate(valid => {
          if (valid) {
            otdrTestResult
              .saveAsTemplate({
                taskId: this.rowData.taskId,
                tempName: this.templateData.templateName,
                logData: {
                  startTime: this.rowData.startTime,
                  deviceName: this.rowData.deviceName,
                  portName: this.rowData.portName,
                  connDeviceName: this.rowData.connDeviceName,
                  taskName: this.rowData.taskName
                }
              })
              .then(res => {
                if (res) {
                  this.$message.success(this.$t('SAVE_SUCCESS'))
                  this.showSaveTemplate = false
                  this.detailData.isTemp = true
                  this.$emit('loadData')
                }
              })
          }
        })
      },
      async updateCable() {
        if (!this.rowData.cableIdList || !this.rowData.cableIdList.length) {
          this.$message.error(this.$t('NO_AVAILABLE_DATA'))
          return
        }
        if (this.rowData.cableIdList && this.rowData.cableIdList.length > 1) {
          this.$message.error(this.$t('ONE_MORE_CABLES'))
          return
        }
        if (!this.rowData.fiberLength) {
          this.$message.error(this.$t('NO_UPDATABLE_LENGTH'))
          return
        }
        const promissArr = this.rowData.cableIdList.map(i => {
          return cableApi.getByCableId({ cableId: i })
        })
        let cableNames = []
        Promise.all(promissArr).then(res => {
          cableNames = res.map(i => i.cableName)
          otdrTestResult
            .updateCableLength({
              taskId: this.rowData.taskId,
              cableIdList: this.rowData.cableIdList,
              fiberLength: changeDecimal(this.rowData.fiberLength, 3, true),
              logData: {
                cableNames: cableNames.join()
              }
            }).then(res => {
              if (res) {
                this.$message.success(this.$t('SAVE_SUCCESS'))
                this.$emit('loadData')
              }
            })
        })
      },
      // 测试类型
      getTestType(type) {
        return type ? this.dictMap.OTDR_TEST_MODE[type] : ''
      },
      exportChannel() {
        console.log('this.rowData.', this.rowData)
        tableToExcel(
          'eventTable',
          this.$t('TEST_EVENT_EXPORT_NAME', {
            segmentName: this.detailData.taskName || '',
            aNodeName: this.detailData.deviceName || this.detailData.deviceId || '',
            portName: this.detailData.portName || this.detailData.portId,
            zNodeName: this.detailData.connDeviceName || this.detailData.connDeviceId || '',
            testTime: this.detailData.startTime.replace(/:/g, '：')
          })
        )
        this.addLog(this.detailData) // OTDR测试记录 导出通道列表
      },
      addLog() {
        let item = 'MENU_BUSINESS_MANAGER'
        if (this.parentVM.functionName === 'homeTopo') {
          item = 'HOME_TOPOLOGY_MAP' // 系统首页-拓扑图
        }
        if (this.parentVM.functionName === 'homeGis') {
          item = 'HOME_GIS_MAP' // 系统首页-GIS展示
        }
        if (this.parentVM.functionName === 'manager') {
          item = 'MENU_BUSINESS_MANAGER' // 业务管理
        }
        let terminal = 'EXPORT_OTDR_SINGLE_CORE_EVENT' // 导出（OTDR测试记录单芯事件列表）
        let i18nKey = 'EXPORT_OTDR_SINGLE_CORE_EVENT_LOG'
        if (this.rowData.bizChannelList.length === 2) {
          if (this.rowData.index === 0) {
            terminal = 'EXPORT_OTDR_DOUBLE_CORE_1_EVENT' // 导出（OTDR测试记录双芯第一芯事件列表）
            i18nKey = 'EXPORT_OTDR_DOUBLE_CORE_1_EVENT_LOG'
          } else if (this.rowData.index === 1) {
            terminal = 'EXPORT_OTDR_DOUBLE_CORE_2_EVENT' // 导出（OTDR测试记录双芯第二芯事件列表）
            i18nKey = 'EXPORT_OTDR_DOUBLE_CORE_2_EVENT_LOG'
          }
        }
        const obj = {
          api: '/',
          item: item,
          object: this.rowData.bizName + '-' + this.rowData.testTime,
          terminal: terminal,
          operateResult: true,
          realName: this.getUser.realName,
          content: JSON.stringify({
            bizName: this.rowData.bizName || '--',
            currentUserId: this.getUser.userId || '--',
            testTime: this.rowData.testTime || '--',
            i18nKey: i18nKey
          })
        }
        // 记录登录日志
        OperateLogApi.addLog(obj)
      },
      close(load) {
        this.rowList = []
        this.referenceData = null
        this.errMsg = ''
        this.criteria = {}
        this.$refs.recordLine && this.$refs.recordLine.distoryChart()
        this.detailData = this.$options.data().detailData
        this.$emit('close', load)
      }
    }
  }
</script>

<style lang="scss">
  @import 'src/assets/css/mixin.module';
  .printHtml {
    padding: 0 5px;
    box-sizing: border-box;
    @include themeify {
      background: themed('dialogBgColor');
    }
  }
  .test-message {
    border: 1px solid #ebeef5;
    @include themeify {
      border: 1px solid themed('borderColor');
    }

    .flex span {
      margin-top: 10px;
      width: 50%;
      &.w-100 {
        width: 100%;
      }
    }
  }
  .test-message-bottom {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    padding: 10px 0;
    & > div {
      display: flex;

      & > i {
        margin-right: 10px;
        font-size: 20px;
      }
      h6 {
        font-size: 14px;
        font-weight: 400;
        color: #12e8ff;
        // white-space: nowrap;
        white-space: pre;
        @include themeify {
          color: themed('textFontColor');
        }
      }
    }
  }
</style>
